<?php

namespace ApiBundle\Controller;

use ApiBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class PublicController extends BaseController
{
    /*
     * 名片注册,添加企业联系人
     */

    public function cardRegisterAction(Request $request)
    {
        $is_register = $request->get("is_register");// 0  添加企业联系人 1名片注册
        $phone = $request-> get("phone");
        $name = $request -> get("name");
        $company = $request -> get("company");
        $position = $request -> get("position");
        $company_address = $request ->get("company_address");
        $email = $request->get("email");

        $password = substr($phone,-6,6);

//        if($is_register == "0" || $is_register == ""){
//            $category_id = $request->get("category_id");
//            //$district = $request->get("district");
//            $attribute_id = $request->get("attribute_id");
//            $admin_id = $request->get("admin_id");
//        }


        // TODO 1: 验证
        $validations = $this->get("helper.validations");
        $serviceStrings = $this->get("helper.strings");

        if(!$phone || !$validations->isMobile($phone))
        {
            return $this->jsonResponse(1,"手机号格式不正确");
        }


        // 姓名验证
        $name_length = mb_strlen($name, "utf8");
        if($name_length > 15 || $name_length < 2)
        {
            return $this->jsonResponse(3,"姓名长度在2~15之间");
        }

        $posi_length = mb_strlen($position,"utf8");
        if($posi_length > 15 || $posi_length < 2)
        {
            return $this->jsonResponse(3,"职位长度在2~15之间");
        }


        if(!$email || !$validations->isEmail($email)){
            return $this->jsonResponse(2,"邮箱格式不正确");
        }
        if($company_address == ""){
            return $this->jsonResponse(2,"公司地址不能为空");
        }


        // 判断手机号是否存在
        $conn = $this->get("database_connection");

        if($this->checkPhoneExit($phone)){
            return $this->jsonResponse(3,"该联络人已存在");
        }

        // TODO :  公司名称判断  暂没有判断管理员名下的企业
        $is_company = $conn->fetchAssoc("SELECT * FROM company WHERE name = '". $company ."'");

        if(!$is_company){
            //return $this->jsonResponse(1,"企业不存在，用工商接口");

            // 工商接口
            $company_url = "http://v.juhe.cn/youshu/query?key=5f8549bbbbf5a201dd71e0ea4beeca56&name=". urlencode($company);

            $new_company = $this->curl($company_url);

            if($new_company->error_code == 0){

                // 获取企业数据，插入数据库
                $conn->insert("company",$this->insertCompany($new_company));

                $new_company_id = $conn->lastInsertId();
                $new_company_address = $new_company->result->address;

                /*
                 * TODO 商标查询
                 */
                $pageSize = "10";
                $curr_page = "1";
                $mark_init_url = "http://japi.juhe.cn/trademark/search?key=48fc7d3240edf38df9daaebebbdc1218&keyword=". urlencode($company);
                $mark_url = $mark_init_url ."&pageSize=".$pageSize;
                $mark_url .="&pageNo=".$curr_page;

                $new_mark = $this->curl($mark_url);

                //var_dump($new_mark);exit;

                // 插入数据库 company表




                /*
                 * TODO 专利查询
                 */
                $next_page = "1";
                $page_size = "10";
                $patent_init_url = "http://v.juhe.cn/patent/search.php?key=85f7fe87ab8a171a0e8f307e4d5a6bf8&q=". urlencode($company);

                $patent_url = $patent_init_url . "&p=".$next_page;
                $patent_url = $patent_url . "&ps=".$page_size;


                $new_pant = $this->curl($patent_url);

                $patent_data = $new_pant->result->patents;

                //第一页 插入专利数据
                foreach ($patent_data as $item){

                    // 插入专利数据
                    $item2 = json_decode(json_encode($item),true);
                    $conn->insert("company_patent",$this->insertPatent($item2,$new_company_id));

                }

                // 查找下一页的专利 非第一页

                $all_pages_count = $new_pant->result->totalPages;
                $page_next_page = $new_pant->result->nextPage;
                for($i=1;$i<$all_pages_count;$i++){

                    if($page_next_page > 0){

                        $page_url = $patent_init_url . "&p=".$page_next_page. "&ps=".$page_size;
                        $page_new_pant = $this->curl($page_url);


                        $page_patent_data = $page_new_pant->result->patents;

                        $page_next_page = $page_new_pant->result->nextPage;

                        foreach ($page_patent_data as $item_a){
                            // 插入专利数据
                            $item2 = json_decode(json_encode($item_a),true);
                            //dump($this->insertPatent($item2,$new_company_id));
                            $conn->insert("company_patent",$this->insertPatent($item2,$new_company_id));
                        }

                    }




                }


            } else {
                return $this->jsonResponse(1,"企业查询：".$new_company->reason);
            }

        } else {
            $new_company_id = $is_company['id'];
            $new_company_address = $is_company['address'];

        }

        $salt = $serviceStrings->generateSalt(6,true);
        $encryptPassword = $serviceStrings->encryptPassword($password,$salt);
        $created_at = date("Y-m-d H:i:s");

        $new_user = array(
            "phone" => $phone,
            "salt" => $salt,
            "password" => $encryptPassword,
            "name" => $name,
            "company_full_name" => $company,
            "position_name" => $position,
            "created_at" => $created_at,
            //"company_address" => $company_address,
            "email" => $email,
            "company_id" => $new_company_id,
            "company_address" => $new_company_address
        );

        if($is_company){
            $new_user['district_id'] = $is_company['district_id'];
        }

//        // 判断企业信息是否完善
//        if($is_register == '0' || $is_register == ""){
//            $data = $conn->fetchAssoc("SELECT company_category_id FROM company WHERE id = '". $is_company['id'] ."' ");
//
//            // 企业信息不完善  需要传参
//            if($data['company_category_id'] == NULL){
//
//                if(empty($category_id) || empty($attribute_id) || empty($admin_id)){
//                    return $this->jsonResponse(1,"参数错误");
//                }
//
//
//                $new_company = array(
//                    "company_attribute_id" => $category_id,
//                    "company_category_id" => $attribute_id,
//                    "admin_id" => $admin_id
//                );
//
//                $conn->update("company",$new_company,array("id" => $is_company['id']));
//
//            } else {
//
//                if($category_id != "" || $attribute_id != "" || $admin_id != ""){
//                    var_dump(123);
//                    return $this->jsonResponse(1,"企业信息已完善，不可修改");
//                }
//            }
//        }



        $result = $conn->insert("user",$new_user);

        if($result){
            return $this->jsonResponse(0,"操作成功");
        }

    }

    /*
     * 获取区域
     */
    public function getDistrictAction(){
        $conn = $this->get("database_connection");
        $data = $conn->fetchAll("SELECT * FROM district WHERE 1");

        return $this->jsonResponse(0,"操作成功",$data);
    }

    /*
     * 企业类别
     */
    public function getCompanyCategoryAction()
    {
        $conn = $this->get("database_connection");
        $data = $conn->fetchAll("SELECT * FROM company_category WHERE 1");

        return $this->jsonResponse(0,"操作成功",$data);
    }

    /*
     * 企业属性
     */
    public function getCompanyAttributeAction()
    {
        $conn = $this->get("database_connection");
        $data = $conn->fetchAll("SELECT * FROM company_attribute WHERE 1");

        return $this->jsonResponse(0,"操作成功",$data);
    }

    /*
     * 获取科技载体列表
     */
    public function getGeneralAdministratorAction()
    {
        $conn = $this->get("database_connection");
        $data = $conn->fetchAll("SELECT * FROM admin WHERE admin_role_id = 4");

        return $this->jsonResponse(0,"操作成功",$data);
    }

    /*
     * 获取科技载体列表  区域内的
     */
    public function getDistrictGeneralAdministratorAction(Request $request)
    {
        $district_id = $request->get("district_id");
        $conn = $this->get("database_connection");
        $data = $conn->fetchAll("SELECT * FROM admin WHERE admin_role_id = 4 AND district_id = '". $district_id ."'");

        return $this->jsonResponse(0,"操作成功",$data);
    }

    /**
     * 上传图片 1：上传头像，2：上传身份证 3: 上传学生证
     *
     * @return JsonResponse
     */
    public function uploadImageAction(Request $request)
    {

        if (isset($_FILES['image']) && $_FILES['image']['name']) {
            $date = date('Ym');
            $path = $this->getParameter('dir_upload') . DIRECTORY_SEPARATOR . $date . DIRECTORY_SEPARATOR;
            $data = $this->uploadImage('image', $path, uniqid());

            if (isset($data['path'])) {
                $result = array('errorCode' => 0, 'message' => '', 'data' => array('path' => $data['path']));
            } else {
                $result = array('errorCode' => 1, 'message' => current($data['errors']));
            }
        } else {
            $result = array('errorCode' => 2, 'message' => '请上传图片');
        }

        return new JsonResponse($result);
    }


    /**
     * 上传附件
     *
     * @return JsonResponse
     */
    public function uploadAttachmentAction(Request $request)
    {

        if (isset($_FILES['attachment']) && $_FILES['attachment']['name']) {
            $date = date('Ym');
            $path = $this->getParameter('dir_upload') . DIRECTORY_SEPARATOR . $date . DIRECTORY_SEPARATOR;
            $data = $this->uploadImage('attachment', $path, uniqid());


            if (isset($data['path'])) {
                $conn = $this->get('database_connection');
                $conn->insert('attachment', array(
                    'path' => $data['path'],
                    'origin_name' => $data['origin_name'],
                    'size' => $data['size'],
                    'created_at' => $data['created_at']
                ));

                $result = array('errorCode' => 0, 'message' => '', 'data' => array('attachment_id' => $conn->lastInsertId(),'name'=>$data['origin_name']));
            } else {
                $result = array('errorCode' => 1, 'message' => current($data['errors']));
            }
        } else {
            $result = array('errorCode' => 2, 'message' => '上传附件过大,请重新上传');
        }

        return new JsonResponse($result);
    }

    /**
     * 发送短信
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getSaltAction(Request $request)
    {
        $type = $request->get('type');
        $phone = $request->get('phone');
        $role = $request->get('role'); // 1 用户微信小程序 2 管理端微信小程序 3普通管理员/超级管理员 4平台管理员

        if (!in_array($role, array(1,2,3,4))) {
            return new JsonResponse(array('errorCode' => 1, 'message' => 'role非法'));
        }

        if (in_array($role, array(2,3,4))) {
            $is_admin = 1;
        } else {
            $is_admin = 0;
        }

        $validations = $this->get("helper.validations");

        if (!$validations->isMobile($phone)) {
            $error = '手机号码格式不正确！';
        } else {
            switch ($type) {
                // 用户注册:
                case parent::SMS_USER_REGISTER:
                    $error = $this->publicCheckPhoneIfExisted($phone, $is_admin) ? '该手机号码已存在' : '';
                    break;
                // 用户找回密码
                case parent::SMS_USER_FORGET_PASSWORD:
                    $error = $this->publicCheckPhoneIfExisted($phone, $is_admin) ? '' : '该手机号码不存在';
                    break;
                // 管理员-找回密码
                case parent::SMS_ADMIN_FORGET_PASSWORD:
                    $error = $this->publicCheckPhoneIfExisted($phone, $is_admin) ? '' : '该手机号码不存在';
                    break;
                // 平台管理员找回密码
                case parent::SMS_PLATFORM_ADMIN_FORGET_PASSWORD:
                    $error = $this->publicCheckPhoneIfExisted($phone, $is_admin) ? '' : '该手机号码不存在';
                    break;
                case parent::SMS_UNKNOWN:
                    $error = '';
                    break;
                default :
                    $error = '非法请求';
            }
        }

        if ($error) {
            return new JsonResponse(array('errorCode' => 1, 'message' => $error));
        }

        $error = $this->sendMessage($phone, $type, $role);

        return new JsonResponse(array('errorCode' => $error ? 1 : 0, 'message' => $error ? $error : '发送成功','salt'=>$error ? '': $this->salt));
    }

    private function publicCheckPhoneIfExisted($phone, $is_admin)
    {
        $conn = $this->get("database_connection");

       return $conn->fetchColumn("SELECT 1 FROM user WHERE phone = '". $phone ."' LIMIT 1")
           || $conn->fetchColumn("SELECT 1 FROM admin WHERE phone = '". $phone ."' LIMIT 1");


    }

    // 发送短信通知
    public function noticePhoneMessageAction(Request $request)
    {
        $user_ids = $request->get("user_ids","[]");
        $user_id_decode = json_decode($user_ids,TRUE);

        $conn = $this->get("database_connection");

        foreach($user_id_decode as $item){
            $user_phone = $conn->fetchAssoc("SELECT * FROM user WHERE id = '". $item ."'");


            $error = $this->sendMessage($user_phone['phone'], 5, 1);
            
            //return $this->jsonResponse(array("errorCode" => $error ? 1 : 0, 'message' => $error ? $error : '发送成功'));
        }

        return $this->jsonResponse(0,"操作成功");

    }

    // 发邮件通知
    public function noticeMailAction(Request $request)
    {
        $user_ids = $request->get("user_ids","[]");
        $user_id_decode = json_decode($user_ids,TRUE);

        $conn = $this->get("database_connection");

        foreach($user_id_decode as $item){
            $user_phone = $conn->fetchAssoc("SELECT * FROM user WHERE id = '". $item ."'");


            $this->emailAction($user_phone['email']);

            //return $this->jsonResponse(array("errorCode" => $error ? 1 : 0, 'message' => $error ? $error : '发送成功'));
        }

        return $this->jsonResponse(0,"操作成功");
    }

    /*
     * 通过training_id获取培训参与人员详情
     */
    public function trainingMemberDetailAction(Request $request)
    {
        $conn = $this->get("database_connection");

        $training_id = $request->get("training_id");

        if(empty($training_id)){
            return $this->jsonResponse(1,"training_id为空");
        }

        $sql = "SELECT * FROM user WHERE id IN (SELECT user_id FROM apply WHERE training_id = '". $training_id ."')";
        $data = $conn->fetchAll($sql);

        return $this->jsonResponse(0,"操作成功",array("data"=>$data));
    }
}
